# -*- coding: utf-8 -*-
import scrapy
from kst.items import DartStockItem

url_search = 'http://dart.fss.or.kr/corp/searchCorp.ax'
stock_num = '137940'

key_num = 'hiddenCikCD1'
key_name = 'hiddenCikNM1'


class FssOrSearchSpider(scrapy.Spider):
    name = 'fss_or_search'
    allowed_domains = ['dart.fss.or.kr']
    start_urls = [url_search]

    def start_requests(self):
        return [scrapy.FormRequest(url_search,
                                   formdata={'textCrpNm': stock_num},
                                   callback=self.parse)]

    def parse(self, response):
        filename = 'RESULT_SEARCH'
        with open(filename, 'wb') as f:
            f.write(response.body)

        td = response.xpath('//fieldset/div/table/tbody/tr')[0].xpath('./td')[0].xpath('div')
        item = DartStockItem()
        item['code'] = stock_num
        for input_data in td.xpath('./input'):
            name = input_data.xpath('./@name').extract_first().strip()
            value = input_data.xpath('./@value').extract_first().strip()
            if name == key_name:
                item['name'] = value
            elif name == key_num:
                item['number'] = value

        print item


            # tr = Selector(response=response).xpath('//fieldset/div/table/tbody/tr')[0]

            # for td in response.xpath('//fieldset/div/table/tbody/tr/td'):
            #     print td
